//
//  ANShoppingCarViewController.m
//  Ants
//
//  Created by ZHM on 16/3/15.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANShoppingCarViewController.h"
#import "ANShoppingCarCell.h"
#import "ANShoppingCarCellFrame.h"
#import "ANUserLoginViewController.h"
#import "ANNavigationVC.h"
#import "ANShoppingCartEndView.h"
#import "UIBarButtonItem+item.h"
#import "ANOptionsView.h"
#import "ANProductViewController.h"


@interface ANShoppingCarViewController ()<UITableViewDataSource,UITableViewDelegate,ANShoppingCartEndViewDelegate,ANShoppingCarCellDelegate,ANOptionsViewDelegate>
@property (nonatomic, weak) UITableView  *tableView;
@property (nonatomic, weak) ANShoppingCartEndView  *endView;
@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UIBarButtonItem *previousBarButton;
@property (nonatomic, strong) UIButton *loginBtn;
@end

@implementation ANShoppingCarViewController

- (UIButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake((ANKeyWindow.width - 100)/2, 150, 100, 30);
        [_loginBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [_loginBtn setTitle:@"点击登录" forState:(UIControlStateNormal)];
        [_loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
        self.view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_loginBtn];
    }
    return _loginBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (![sharedWebService isLoggedIn]) {
        self.loginBtn.hidden = NO;
        self.tableView.hidden = YES;
    }else {
        self.tableView.hidden = NO;
        self.loginBtn.hidden = YES;
    }
    
    //右边
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemCilck:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ANKeyWindow.width, ANKeyWindow.height) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    _tableView = tableView;
    [self.view addSubview:tableView];
    _endView = [ANShoppingCartEndView shoppingCartEndViewWithVC:self];
    
    //边界
    if (self.hidesBottomBarWhenPushed) {
        self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 44, 0);
    } else {
        self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 44 + 49, 0);
    }
    
    //监听键盘的弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshShoppingCarTableView) name:@"RefreshShoppingCar" object:nil];
}
- (void)refreshShoppingCarTableView {
    [self.tableView reloadData];
}

#pragma mark -- 键盘Frame改变时候调用
- (void)keyboardFrameChange:(NSNotification *)notification {
    //获取键盘动画时间
    CGFloat time = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //获取键盘Frame
    CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (frame.origin.y == ANKeyWindow.height) {
        [UIView animateWithDuration:time animations:^{
            //还原
            self.toolbar.transform = CGAffineTransformIdentity;
        }];
    } else {
        [UIView animateWithDuration:time animations:^{
            //移动
            self.toolbar.transform = CGAffineTransformMakeTranslation(0, -frame.size.height - 44);
        }];
    }
}
- (UIToolbar *)toolbar {
    if (!_toolbar) {
        _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.height, ANscreenW, 44)];
        [_toolbar setBarStyle:UIBarStyleDefault];
        
        UIBarButtonItem *flexBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        self.previousBarButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(previousButtonIsClicked:)];
        NSArray *barButtonItems = @[flexBarButton,self.previousBarButton];
        _toolbar.items = barButtonItems;
        [self.view addSubview:_toolbar];
    }
    return _toolbar;
}

- (void) previousButtonIsClicked:(id)sender {
    [self.view endEditing:YES];
}
- (void)rightItemCilck:(UIBarButtonItem *)item {
    self.isEdit = !self.isEdit;
    if (self.isEdit) {
        item.title = @"取消";
        for (ANShoppingCarCellFrame *cellItem in sharedWebService.shoppingItems) {
            cellItem.isSelect = NO;
        }
    }
    else{
        item.title = @"编辑";
        for (ANShoppingCarCellFrame *cellItem in sharedWebService.shoppingItems) {
            cellItem.isSelect = NO;
        }
        ANLog(@"计算价格");
        [self statTotalPrice];
    }
    _endView.isEdit = self.isEdit;
    [_tableView reloadData];
}
- (void)loginClick {
    ANUserLoginViewController *userLoginVC = [[ANUserLoginViewController alloc] init];
    ANNavigationVC *nav = [[ANNavigationVC alloc] initWithRootViewController:userLoginVC];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return sharedWebService.shoppingItems.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ANShoppingCarCell *cell = [ANShoppingCarCell cellWithTableView:tableView];
    cell.model = sharedWebService.shoppingItems[indexPath.row];
    cell.isEdit = self.isEdit;
    cell.delegate = self;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ANShoppingCarCellFrame *itemFarme = sharedWebService.shoppingItems[indexPath.row];
    return itemFarme.cellHeight;
}

#pragma mark  --CELL代理方法 计算总价
- (void)statTotalPrice:(ANShoppingCarCell *)cell {
    //计算价格
    [self statTotalPrice];
}
- (void)statTotalPriceWithSelectBtn:(ANShoppingCarCell *)cell {
    //计算价格
    [self statTotalPrice];
    
    if (cell.model.isSelect) {
        BOOL allSelect = YES;
        for (ANShoppingCarCellFrame *model in sharedWebService.shoppingItems) {
            if (!model.isSelect) {
                allSelect = NO;
            }
        }
        _endView.selectBut.selected = allSelect;
    } else {
        _endView.selectBut.selected = NO;
    }
}
- (void)showProduct:(ANBDProduct *)product {
    if (!_isEdit) {
        ANProductViewController *productVC = [[ANProductViewController alloc] init];
        productVC.product = product;
        productVC.isFromShoppingCar = YES;
        //当PUSH时候就会隐藏底部条
        productVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:productVC animated:YES];
    }
}
- (void)statTotalPrice {
    float num = 0.00;
    for (ANShoppingCarCellFrame *model in sharedWebService.shoppingItems) {
        if (model.isSelect) {
            num = model.count * [model.shoppingItem.product.price intValue] + num;
        }
    }
    _endView.priceLab.text = [NSString stringWithFormat:@"￥ %.2f",num];
}
- (void)clickRightBut:(UIButton *)but {

    if (_isEdit) {
        [ANOptionsView optionsViewWithTitle:@"删除" delegate:self];
    } else {
        ANLog(@"结算");
    }
}
- (void)optionsView:(ANOptionsView *)optionsView didClickBtn:(NSInteger)index {
    if (index == 1) {
        if (optionsView.isCellDele) {
            ANShoppingCarCellFrame *model = sharedWebService.shoppingItems[optionsView.tag];
            [self removeShoppingItemAtModel:model];
            [sharedWebService.shoppingItems removeObjectAtIndex:index];
            [self.tableView reloadData];
        } else {
            [self removeShoppingItems];
            [self.tableView reloadData];
        }
    }
}
- (void)removeShoppingItemAtModel:(ANShoppingCarCellFrame *)model {
    
    [sharedWebService removeShoppingItem:model.shoppingItem completion:nil];
}
- (void)removeShoppingItems {
    NSMutableArray *removeItems = [NSMutableArray array];
    for (ANShoppingCarCellFrame *model in sharedWebService.shoppingItems) {
        if (model.isSelect) {
            ANLog(@"%@",model.shoppingItem.product.title);
            [self removeShoppingItemAtModel:model];
            [removeItems addObject:model];
        }
    }
    for (ANShoppingCarCellFrame *model in removeItems) {
        [sharedWebService.shoppingItems removeObject:model];
    }
}
#pragma mark -cell 删除按钮
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath :(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //删除服务器上的数据
        ANOptionsView *optionsView = [ANOptionsView optionsViewWithTitle:@"删除" delegate:self];
        optionsView.tag = indexPath.row;
        optionsView.isCellDele = YES;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)clickALLEnd:(UIButton *)but {
    but.selected = !but.selected;
    for (ANShoppingCarCellFrame *model in sharedWebService.shoppingItems) {
        model.isSelect = but.selected;
    }
    for (ANShoppingCarCellFrame *model in sharedWebService.shoppingItems) {
        ANLog( @"isSelect=== %d",model.isSelect);
    }
    if (!self.isEdit) {
        ANLog(@"计算价格");
        [self statTotalPrice];
        [self.tableView reloadData];
    }else {
        [self.tableView reloadData];
    }
}
- (void)viewDidLayoutSubviews {

}
- (void)dealloc {
    ANLog(@"%s",__func__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshShoppingCar" object:nil];
}
@end
